import json

from django.http import HttpResponse
from django.shortcuts import render
from django.views import View
from django.http import JsonResponse
from .serializer import BooksSerializer
from books.models import BookInfo


class Books(View):
    def get(self, request):
        books = BookInfo.objects.all()
        ser = BooksSerializer(books, many=True)
        return JsonResponse(ser.data, safe=False)

    def post(self, request):
        data = request.body.decode()
        data_dict = json.loads(data)
        # 验证数据
        ser = BooksSerializer(data=data_dict)
        # 修改时
        # ser = BooksSerializer('查询集对象', data=data_dict)
        # 验证错误直接报错
        ser.is_valid(raise_exception=True)
        # 获取验证成功后的字段
        # print(ser.validated_data)
        # 保存书据 看序列类参数是否传递　决定创建还是更改
        ser.save()
        # 响应
        return JsonResponse(ser.data)

    def put(self, request, pk):
        data = request.body.decode()
        data_dict = json.loads(data)
        try:
            book = BookInfo.objects.get(pk=pk)
        except:
            return HttpResponse('错误')
        # 验证数据
        # ser = BooksSerializer(data=data_dict)
        # 修改时
        ser = BooksSerializer('查询集对象', data=data_dict)
        # 验证错误直接报错
        ser.is_valid(raise_exception=True)
        # 获取验证成功后的字段
        # print(ser.validated_data)
        # 保存书据 看序列类参数是否传递　决定创建还是更改
        ser.save()
        # 响应
        return JsonResponse(ser.data)
# Create your views here.
